package com.gem.netty.message;

import com.gem.entity.Game;
import com.gem.entity.Log;
import com.gem.enums.ClientMessageType;
import com.gem.enums.GameRoundStageType;
import com.gem.factory.game.GameFactory;
import com.gem.factory.log.LogFactory;
import com.gem.factory.user.UserFactory;
import com.gem.netty.entity.ClientContent;
import com.gem.netty.entity.CurrentUser;
import com.gem.netty.delay.SkipRound;
import com.gem.netty.session.GroupSessionFactory;
import com.gem.utils.R;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.Date;
import java.util.List;

/**
 * Author: Xhy
 * CreateTime: 2022-09-21 19:01
 * 到当前玩家回合阶段
 */
@Deprecated
public class RoundBeganMessage implements Message{

    @Override
    public void handler(ClientContent content) {
        Game game = GameFactory.get(content.getRoomId());
        String roomId = game.getRoomId();
        // 删除延迟队列中记录之前用户的记录
        SkipRound.getInstance().remove(game);
        // 监听当前用户当前回合时长
        SkipRound.getInstance().add(game,60);

        List<Channel> channels = null;
        // 是否有获胜玩家
        if (tryWin(game)){
            // 多个玩家 >= 15分的情况下选出分最大的
            CurrentUser user = game.getWins().poll();
            channels = GroupSessionFactory.getGroupSession().getMembersChannel(game.getRoomId());
            for (Channel channel : channels) {
                channel.writeAndFlush(new TextWebSocketFrame(R.ok().message(UserFactory.get(user.getId() + " 获得了胜利,得分:" + user.getOwnScore())).type(ClientMessageType.GAME_END.type).toString()));
            }
            return;
        }
        // 通知其他玩家不可操作
         channels = GroupSessionFactory.getGroupSession().getMembersChannel(game.getRoomId());
        // 修改当前用户为拿宝石阶段
        CurrentUser user = game.getUsers().get(game.getCurrentIndex());
        String userName = user.getName();
        setGetGem(user);
        for (Channel channel : channels) {
            channel.writeAndFlush(new TextWebSocketFrame(R.ok().message(userName  +" 玩家阶段").type(content.getType()).toString()));
        }
        Log log = new Log();
        log.setMessage(userName  +" 玩家阶段");
        log.setDate(new Date());
        LogFactory.add(roomId,log);
    }

    private void setGetGem(CurrentUser user) {
        user.setState(GameRoundStageType.GET_GEM.type);
    }


    // 是否有胜利的玩家
    private boolean tryWin(Game game) {

        // 判断下一个玩家是否是新的回合,当前索引处 +1 % 房间内的玩家 == 0 说明下一个回合为新的回合
        if ((game.getCurrentIndex() +1) % game.getUsers().size() == 0){
            return true;
        }


        return false;
    }
}
